// ==UserScript==
// @name        Better Omega-Day
// @namespace   BOD
// @description Better Omega-Day
// @include     http://*.omega-day.*/game/*
// @require     http://code.jquery.com/jquery-1.8.2.min.js
// @updateURL   https://better-omega-day.googlecode.com/svn/update.js
// @installURL  https://better-omega-day.googlecode.com/svn/better_od.user.js
// @downloadURL https://better-omega-day.googlecode.com/svn/better_od.user.js
// @version     0.9g
// @grant       GM_getValue
// @grant       GM_setValue
// @grant       GM_listValues
// @grant       GM_deleteValue
// @grant       GM_xmlhttpRequest
// ==/UserScript==
 
if(typeof(console) === 'undefined') {
	var console = {};
	console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function(){};
}
 
$(document).ready(function(){
		BOD.init();    
	   
		if(BOD.settings.fix_planet) BOD.fix_planet_list();
	   
		if(BOD.search.op == 'planet'){
				if(BOD.settings.geb_menu) BOD.geb_menu();
				if(BOD.settings.sell_planet) BOD.sell_planet();
		} else if(BOD.search.op == 'ptrade'){
				if(BOD.settings.sell_planet) BOD.renew_sell_planet();
		} else if(BOD.search.op == 'fleet'){
				if(BOD.settings.ship_name) BOD.ship_links();
		} else if(BOD.search.op == 'sview'){
				if(BOD.settings.ship_name) BOD.ship_name();
		} else if(BOD.search.op == 'comm'){
				if(BOD.settings.fix_comm) BOD.fix_comm();
		}
	   
		if(BOD.debug > 1) console.log(BOD.settings);
});
 
var BOD = {
		version: '0.9g',
		versionlink: '',
		debug: 0,
		userid: $(".statusbar .user").attr('href').substr(-7),
		search: new Object(),
		data: new Object(),
		settings: new Object(),
		init: function(){
				BOD.versionlink = 'v' + BOD.version;
				$('<style type="text/css">#BOD_planets {height:auto !important;margin-top:15px !important;}' +
						'#BOD_planets #quickjump {width:auto !important;height:auto !important;overflow:visible !important;' +
								'padding:5px !important;border:1px solid #15607F !important;-moz-border-radius:5px !important;border-radius:5px !important;}' +
						'#BOD_planets #quickjump-layer {width:100% !important;height:100% !important;padding:0 !important;margin:-1px 0pt 0pt -1px;' +
								'border:1px solid transparent !important;}' +
						'#BOD_planets #quickjump table {width:100% !important;}' +
						'#BOD_sell_planet_form td {padding:5px 0;}' +
						'#BOD_gesamt_tr td {border-top:4px double #EEEEEE;}' +
						'#BOD_settings {background-color:#000723;border:1px solid #15607F;border-radius:5px;-moz-border-radius:5px;width:185px;font-size:12px;text-align:center;margin-top:10px;}' +
						'#BOD_settings a {height:16px;display:inline;}' +
						'#BOD_settings a:hover {background-color:#004065;text-decoration:none;}' +
						'#BOD_settings hr {border-width:0 !important;margin:2px 5px !important;padding:0 !important;height:1px !important;}' +
						'#BOD_settings_dialog .message {color:#00FF00;}' +
						'#BOD_settings_dialog .error {color:#FF0000;}' +
						'#BOD_settings_dialog hr {border-width:0 !important;margin:2px 5px !important;padding:0 !important;height:1px !important;}</style>').appendTo('head');
	   
				var querystring = window.location.search.substr(1);
				var pairs = querystring.split("&");
				for(var i = 0; i < pairs.length; i++){
						var keyValuePair = pairs[i].split("=");
						BOD.search[keyValuePair[0]] = keyValuePair[1];
				}
 
				var body_html = $("body").html();      
			   
				if(body_html.match(/Willkommen in Omega-Day/)){
						var keys = GM_listValues();
						for(var i = 0, key = null; key = keys[i]; i++){
								if(key == 'firstrun') continue;
								GM_deleteValue(key);
								if(BOD.debug > 0) console.log('GM_deleteValue(' + key + ')');
						}
				} else if(BOD.search.op == 'planet'){
						BOD.data.minpreis = body_html.match(/minpreis = (\d{1,9})/)[1];
						BOD.data.planetid = body_html.match(/planet_id = (\d{1,9})/)[1];
				}
 
				BOD.read_settings();
				BOD.check_version();
			   
				$(".menu").append('<li id="BOD_settings">' +
														'Better Omega-Day<br />' +
														'<a id="BOD_open_settings" href="javascript:$.globalEval(\'new Dialog(\\\'BOD_dialog\\\');Dialog.get(\\\'BOD_dialog\\\').openAndCenter();\');" style="height:16px;">Settings</a><br />' +
														'<a href="javascript:donix();">Info</a><hr /><a href="http://www.simod.gdra.de/pkr9/" target="_blank">Planetenkonfigurator</a><br />' +
														'<a href="http://www.omega-day.com/game/shipconfigurator/" target="_blank">Schiffskonfigurator</a><hr /><small><span id="BOD_version">' + BOD.versionlink + '</span> - &copy; <a href="?op=usershow&welch=1000209">Timmaeh</a></small></li>');
			   
				$("#BOD_open_settings").on('click', function(){
						BOD.open_settings($(this).attr('id'));
				});
			   
		},
		check_version: function(){
				GM_xmlhttpRequest({
						method: 'POST',
						url: 'http://www.timmaeh.de/betterod/sync.php',
						data: 'action=version&userid=' + BOD.userid + '&data=' + BOD.version,
						headers: {"Content-Type": "application/x-www-form-urlencoded"},
						onload: function(response){
								var responseJSON = $.parseJSON(response.responseText);
								if(!responseJSON.up2date) $('#BOD_version').html('<a href="https://better-omega-day.googlecode.com/svn/better_od.user.js" target="_blank">' + BOD.versionlink + '</a>');
						}
				});
				return BOD.versionlink
		},
		open_dialog: function(id, title, content){
				if($("#BOD_dialog").length > 0){
						if($("#BOB_opener_id").val() != id) $("#BOD_dialog").remove();
						else return;
				}
				$("#layout-main").append('<div style="width: 440px; left: 180px; top: 50px; visibility: hidden;" class="box dialog" id="BOD_dialog"><input type="hidden" id="BOD_opener_id" value="' + id + '" /><div class="topleft"></div><div class="topright"></div><div class="bottomleft"></div><div class="bottomright"></div><div class="header" id="BOD_dialog_title"><div class="close" id="BOD_dialog_x"><a href="javascript:Dialog.get(\'BOD_dialog\').closeDialog()">X</a></div><div class="title" id="BOD_dialog_tt">' + title + '</div></div><div class="content" id="BOD_dialog_c">' + content + '</div><div class="footer"><a href="javascript:Dialog.get(\'BOD_dialog\').closeDialog()">Schließen</a></div></div>');
		},
		read_settings: function(){
				var sett_arr = GM_listValues();
				var filled = 0;
				
				if($('.sitters_logout').length > 0){
					BOD.userid = GM_getValue('last_used');
				} else {
					GM_setValue('last_used', BOD.userid);
				}
				
				$.each(sett_arr, function(index, sett){
						if(BOD.userid == sett){
								BOD.settings = $.parseJSON(GM_getValue(sett));
								filled = 1;
						}
				});
			   
				if(!filled){
						var standard = '{"save_cloud": false, "fix_planet": true, "geb_menu": true, "sell_planet": true, "fix_comm": true, "ship_name": true}';
						BOD.settings = $.parseJSON(standard);
						GM_setValue(BOD.userid, standard);
						sett_arr = GM_listValues();
				}              
		},
		open_settings: function(id){
				var output = '<table id="BOD_settings_dialog">';
						output += '<tr><td><input type="checkbox" id="fix_comm" name="fix_comm" value="true" '
								output += (BOD.settings.fix_comm) ? 'checked="ckecked"' : '';
								output += '/></td><td align="left"><label for="fix_comm">Comm-Box fixen</label></td>';
						output += '<tr><td><input type="checkbox" id="fix_planet" name="fix_planet" value="true" '
								output += (BOD.settings.fix_planet) ? 'checked="ckecked"' : '';
								output += '/></td><td align="left"><label for="fix_planet">Planetenliste fixen</label></td>';
						output += '<tr><td><input type="checkbox" id="geb_menu" name="geb_menu" value="true" '
								output += (BOD.settings.geb_menu) ? 'checked="ckecked"' : '';
								output += '/></td><td align="left"><label for="geb_menu">Gebäudeliste fixen</label></td>';
						output += '<tr><td><input type="checkbox" id="sell_planet" name="sell_planet" value="true" '
								output += (BOD.settings.sell_planet) ? 'checked="ckecked"' : '';
								output += '/></td><td align="left"><label for="sell_planet">"Planet verkaufen" fixen</label></td>';
						output += '<tr><td><input type="checkbox" id="ship_name" name="ship_name" value="true" '
								output += (BOD.settings.ship_name) ? 'checked="ckecked"' : '';
								output += '/></td><td align="left"><label for="ship_name">Schiffsname in Detailansicht ändern</label></td>';
						output += '<tr><td colspan="2"><input id="BOD_settings_save" type="button" class="tablebutton" value="Einstellungen speichern" /><br />';
						output += '<input type="checkbox" id="save_cloud" name="save_cloud" value="true" '
								output += (BOD.settings.save_cloud) ? 'checked="ckecked"' : '';
								output += '/><label for="save_cloud" style="font-size:10px;">Kopie in der Cloud ablegen</label></td></tr>';
						output += '<tr><td colspan="2"><hr></td></tr>';
						output += '<tr><td colspan="2"><input id="BOD_settings_load" type="button" class="tablebutton" value="Einstellungen aus der Cloud laden" /></td>';
						output += '</table>';
					   
				BOD.open_dialog(id, 'Better Omega-Day - Settings', output);
			   
				$("#BOD_settings_save").on('click', BOD.save_settings);
				$("#BOD_settings_load").on('click', BOD.cloud.load);
			   
		},
		cloud: {
				load: function(){
						$('#BOD_settings_dialog .message, #BOD_settings_dialog .error').remove();
						GM_xmlhttpRequest({
								method: 'POST',
								url: 'http://www.timmaeh.de/betterod/sync.php',
								data: 'action=getdata&userid=' + BOD.userid,
								headers: {"Content-Type": "application/x-www-form-urlencoded"},
								onload: function(response){
										var responseJSON = $.parseJSON(response.responseText);
										if(response.responseText == ''){
												$('#BOD_settings_dialog').prepend('<tr><td class="error" colspan="2">Es ist ein unbekannter Fehler aufgetreten!</td></tr>');
										} else if(responseJSON.error){
												$('#BOD_settings_dialog').prepend('<tr><td class="error" colspan="2">' + responseJSON.error + '</td></tr>');
										} else {                               
												GM_setValue(BOD.userid, response.responseText);
												$('#BOD_settings_dialog').prepend('<tr><td class="message" colspan="2">Einstellungen wurden erfolgreich aus der Cloud geladen!</td></tr>');
										}
								}
						});
				},
				save: function(cloud_string){
						GM_xmlhttpRequest({
								method: "POST",
								url: "http://www.timmaeh.de/betterod/sync.php",
								data: "action=savedata&userid=" + BOD.userid + cloud_string,
								headers: {"Content-Type": "application/x-www-form-urlencoded"},
								onload: function(response){
										var responseJSON = $.parseJSON(response.responseText);
										if(responseJSON.message) $('#BOD_settings_dialog .message').first().parent().after('<tr><td class="message" colspan="2">' + responseJSON.message + '</td></tr>');
										else if(responseJSON.error) $('#BOD_settings_dialog .message').first().parent().after('<tr><td class="error" colspan="2">' + responseJSON.error + '</td></tr>');
								}
						});
				}
		},
		save_settings: function(){
				$('#BOD_settings_dialog .message, #BOD_settings_dialog .error').remove();
				var settings = $("#BOD_dialog :input[type='checkbox']");
				var settings_string = '';
				var cloud_string = '';
				settings.each(function(){
						var key = $(this).attr('name');
						var value = (typeof $(this).attr('checked') != 'undefined') ? true : false;
						BOD.settings[key] = value;
						if(settings_string != '') settings_string += ', ';
						settings_string += '"' + key + '": ' + value;
					   
						if(key != 'save_cloud'){
								if(cloud_string != '') cloud_string += '%26';
								cloud_string += key + '%3D' + value;
						}
				});
				settings_string = '{' + settings_string + '}';
				cloud_string = '&data=' + cloud_string;
			   
				GM_setValue(BOD.userid, settings_string);
			   
				$('#BOD_settings_dialog').prepend('<tr><td colspan="2" class="message">Einstellungen wurden erfolgreich lokal gespeichert!</td></tr>');
			   
				if(BOD.settings.save_cloud) BOD.cloud.save(cloud_string);
		},
		fix_planet_list: function(){
				var menu = $("ul.menu");
				$(menu).attr('id', 'BOD_menu');
				$(menu).find("ul.planets").attr('id', 'BOD_planets');
			   
				$(menu).find("li.favourites").remove();
				$("#BOD_planets li.label").remove();
		},
		sleep: function(ms){
				var dt = new Date();
				dt.setTime(dt.getTime() + ms);
				while (new Date().getTime() < dt.getTime());
		},
		sell_planet: function(){
				$("a[href='javascript:planetVerkauf()']").attr('id', 'BOD_sell_planet').attr('href', "javascript:$.globalEval('new Dialog(\\\'BOD_dialog\\\');Dialog.get(\\\'BOD_dialog\\\').openAndCenter();');");
			   
				$("#BOD_sell_planet").on('click', function(){
						BOD.open_dialog($(this).attr('id'), 'Planet verkaufen', '<form action="?op=ptrade&verkauf=' + BOD.data.planetid +
								'&sell=sell" method="post" name="Formular7">' +
								'<input type="hidden" value="' + BOD.data.planetid + '" name="planetid">' +
								'<input type="hidden" value="' + BOD.data.minpreis + '" name="prizze" id="prizze">' +
								'<table id="BOD_sell_planet_form" width="100%" cellspacing="0">' +
								'<tr><td></td><td align="right">Grundpreis:</td><td><input type="text" class="tableinput" value="' + BOD.data.minpreis + '" id="verkaufenpreis" disabled="disabled" readonly="readonly"></td><td align="left">zzgl. Steuer</td></tr>' +
								'<tr><td style="padding:0;font-size:22px;font-weight: bold;">+</td><td align="right">Zuschlag:</td><td><input type="text" class="tableinput" value="0" id="BOD_zuschlag"></td><td align="left">zzgl. Steuer</td></tr>' +
								'<tr id="BOD_gesamt_tr"><td style="padding:0;font-size:22px;font-weight: bold;">=</td><td align="right">Gesamtpreis:</td><td><input type="text" class="tableinput" value="' + BOD.data.minpreis + '" id="BOD_gesamtpreis"></td><td align="left">zzgl. Steuer</td></tr>' +
								'<tr><td></td><td align="right">An Spieler:</td><td><input type="text" class="tableinput" value="Alle" name="diran" id="diran"></td><td align="left"></td></tr>' +
								'<tr><td colspan="2"></td><td align="center"><input type="submit" class="tablebutton" value="Anbieten" name="Abschicken"></td><td></td></tr>' +
								'</table></form>' +
								'<br /><p style="width:250px;margin-left:95px;">Du kannst einen Planeten <font class="BOD_2much">maximal</font> für das <font class="BOD_2much">7 fache des Mindestpreises</font> verkaufen!</p>');
					   
						$("#BOD_zuschlag").on('keyup', function(){
								var zuschlag = $("#BOD_zuschlag").val();
								zuschlag = zuschlag.replace(/\D/g, '');
								if(zuschlag == '') zuschlag = 0;
								var gesamtpreis = parseInt(BOD.data.minpreis) + parseInt(zuschlag);
								var maximalpreis = parseInt(BOD.data.minpreis) * 7;
								$("#BOD_gesamtpreis, #prizze").val(gesamtpreis);
							   
								$("#BOD_gesamtpreis, #BOD_zuschlag").css('color', '#CCCCFF');
								$(".BOD_2much").css('color', '#EEEEEE');
									   
								if(gesamtpreis > maximalpreis){
										$("#BOD_gesamtpreis, .BOD_2much").css('color', 'red');
										$("#prizze").val(maximalpreis);
								} else if(gesamtpreis < parseInt(BOD.data.minpreis)){
										$("#BOD_zuschlag").css('color', 'red');
										$("#prizze").val(BOD.data.minpreis);
								}
						});
					   
						$("#BOD_gesamtpreis").on('keyup', function(){
								var gesamtpreis = $("#BOD_gesamtpreis").val();
								gesamtpreis = gesamtpreis.replace(/\D/g, '');
								if(gesamtpreis == '') gesamtpreis = 0;
								var zuschlag = parseInt(gesamtpreis) - parseInt(BOD.data.minpreis);
								var maximalpreis = parseInt(BOD.data.minpreis) * 7;
								$("#BOD_zuschlag").val(zuschlag);
								$("#prizze").val(gesamtpreis);
							   
								$("#BOD_gesamtpreis, #BOD_zuschlag").css('color', '#CCCCFF');
								$(".BOD_2much").css('color', '#EEEEEE');
							   
								if(gesamtpreis > maximalpreis){
										$("#BOD_gesamtpreis, .BOD_2much").css('color', 'red');
										$("#prizze").val(maximalpreis);
								} else if(gesamtpreis < parseInt(BOD.data.minpreis)){
										$("#BOD_zuschlag").css('color', 'red');
										$("#prizze").val(BOD.data.minpreis);
								}
						});
				});
			   
		},
		renew_sell_planet: function(){
				$("a[href^='javascript:renewplanetoffer']").each(function(){
						var rel = $(this).attr('href').substr(28);
						$(this).addClass('BOD_renew_sell_planet').attr('rel', rel).attr('href', "javascript:$.globalEval('new Dialog(\\\'BOD_dialog\\\');Dialog.get(\\\'BOD_dialog\\\').openAndCenter();');");
				});
			   
				$(".BOD_renew_sell_planet").on('click', function(){
					   
						var data = $(this).attr('rel').split(', ');
						data[2] = data[2].substr(1, data[2].length-3);
					   
						BOD.open_dialog($(this).attr('id'), 'Planet verkaufen', '<form action="?op=ptrade&renew=renew" method="post" name="Formular7">' +
								'<input type="hidden" value="' + data[0] + '" name="renewid">' +  
								'<input type="hidden" value="' + data[1] + '" name="new_price" id="prizze">' +  
								'<table id="BOD_sell_planet_form" width="100%" cellspacing="0">' +
								'<tr><td></td><td align="right">Alter Preis:</td><td><input type="text" class="tableinput" value="' + data[1] + '" id="verkaufenpreis" disabled="disabled" readonly="readonly"></td><td align="left">zzgl. Steuer</td></tr>' +
								'<tr><td style="padding:0;font-size:22px;font-weight: bold;">+</td><td align="right">Zuschlag:</td><td><input type="text" class="tableinput" value="0" id="BOD_zuschlag"></td><td align="left">zzgl. Steuer</td></tr>' +
								'<tr id="BOD_gesamt_tr"><td style="padding:0;font-size:22px;font-weight: bold;">=</td><td align="right">Neuer Preis:</td><td><input type="text" class="tableinput" value="' + data[1] + '" id="BOD_gesamtpreis"></td><td align="left">zzgl. Steuer</td></tr>' +
								'<tr><td></td><td align="right">An Spieler:</td><td><input type="text" class="tableinput" value="' + data[2] + '" name="new_target" id="diran"></td><td align="left"></td></tr>' +
								'<tr><td colspan="2"></td><td align="center"><input type="submit" class="tablebutton" value="Anbieten" name="Abschicken"></td><td></td></tr>' +
								'</table></form>');
					   
						$("#BOD_zuschlag").on('keyup', function(){
								var zuschlag = $("#BOD_zuschlag").val();
								zuschlag = zuschlag.replace(/[^0-9-]/g, '');
								zuschlag = zuschlag.substr(0, 1) + zuschlag.substr(1, zuschlag.length-1).replace(/-/g, '');
								if(zuschlag == '' || zuschlag == '-') zuschlag = 0;
								var gesamtpreis = parseInt(data[1]) + parseInt(zuschlag);
								$("#BOD_gesamtpreis, #prizze").val(gesamtpreis);
						});
					   
						$("#BOD_gesamtpreis").on('keyup', function(){
								var gesamtpreis = $("#BOD_gesamtpreis").val();
								gesamtpreis = gesamtpreis.replace(/\D/g, '');
								if(gesamtpreis == '') gesamtpreis = 0;
								var zuschlag = parseInt(gesamtpreis) - parseInt(data[1]);
								$("#BOD_zuschlag").val(zuschlag);
								$("#prizze").val(gesamtpreis);
						});
				});
			   
		},
		geb_menu: function(){
				var geb_menu = $("#1000").parentsUntil('div', 'table');
				$(geb_menu).attr('id', 'BOD_geb_menu');
			   
				var id_rules = new Array('#1003;#1016, #1017',
																 '#1005;#1006, #1025',
																 '#1008;#1018, #1019',
																 '#1007;#1014, #1031',
																 '#1000;#1046, #1053',
																 '#1002;#1009;#1010;#1022;#1023, #1037, #1054',
																 '#1027;#1028',
																 '#1001;#1011;#1015;#1038',
																 '#1035;#1051',
																 '#1032;#1034',
																 '#1042;#1044, #1043',
																 '#1004;#1052',
																 '#1013;#1020',
																 '#1013, #1020;#1048, #1040, #1024, #1029');
			   
				$.each(id_rules, function(index, rule){
						var steps = rule.split(';');
						var found = 0;
						steps.reverse();
						$.each(steps, function(step, id_list){                 
								if(found == 0){
										if($(id_list).length > 0){
												if(BOD.debug > 1) console.log('FOUND:', id_list);
												found++;
										} else if(BOD.debug > 1){
												console.log('NOT FOUND:', id_list);
										}
								} else {
										if(BOD.debug > 1) console.log('DELETE:', id_list);
										if($(id_list).length > 0) $(id_list).remove();
								}
						});
				});
			   
				var geb_json = new Object();
			   
				$(geb_menu).find('img').each(function(index, Element){
						var id = $(this).attr('id');
					   
						var curr_geb_json = new Object();
						var attrs = $(this)[0].attributes;
						for(var i = 0; i < attrs.length; i++) curr_geb_json['g' + attrs[i].nodeName] = attrs[i].nodeValue;
					   
						geb_json[id] = curr_geb_json;
					   
				});
			   
				$(geb_menu).html('');
				$.each(geb_json, function(index, curr_geb_json){
						var attributes = new Array();
						$.each(curr_geb_json, function(key, value){
								attributes.push(key.substr(1) + '="' + value + '"');
						});
						$(geb_menu).append('<a onfocus="if(document.all) this.blur()" href="javascript:donix();"><img ' + attributes.join(' ') + ' /></a>');
				});
		},
		ship_links: function(){
				$("a[href^='?op=sview&shipid=']").each(function(index){
						var link = $(this).attr('href') + '&index=' + $(this).parent().next().find("a").attr('href').substr(16);
						$(this).attr('href', link);
				});
		},
		ship_name: function(){
				$("#layout-main").find(".box:first-child").find("td").attr("id", "BOD_ship_name");
				var old_name = $("#BOD_ship_name").children("b").html().substr(7);
				$("#BOD_ship_name").children("b").html('Schiff:&nbsp;&nbsp;<form id="BOD_set_new_ship_name" action="?op=sview&shipid=' + BOD.search.shipid + '" method="POST"><input type="text" id="BOD_new_ship_name" class="tableinput" value="' + old_name + '" /> <input type="submit" class="tablebutton" value="Umbenennen" /></form>');
			   
				$("#BOD_set_new_ship_name").on('submit', function(event){
						var new_name = $("#BOD_new_ship_name").val();
						if(old_name != new_name){
								$.post("?op=orbit&index=" + BOD.search.index + "&rename=rename",
										   {neuname: new_name, ships: BOD.search.shipid},
										   function(){ location.reload(true); });
						}
						event.preventDefault();
				});  
		},
		fix_comm: function(){
				$("div.box").attr("id", "BOD_comm");
				var comm_box = $("#BOD_comm table.tabletrans").find("form[action='?op=comm']")[0];
				$(comm_box).children("div[align='center']").css("height", "auto");
				$("#BOD_comm > div > div[align='center']").css("height", "auto");
		}
}